<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="数组,Math,函数式编程,原型链," />





  <link rel="alternate" href="/atom.xml" title="jackfred的博客" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.2" />






<meta name="description" content="凡是存在的就是合理的，那些说函数式编程可读性差的，你就是不会啊！">
<meta property="og:type" content="article">
<meta property="og:title" content="函数式编程:用自带的js原型链方法解决问题">
<meta property="og:url" content="https://zk-.github.io/2016/10/23/函数式编程-用自带的js原型链方法解决问题/index.html">
<meta property="og:site_name" content="jackfred的博客">
<meta property="og:description" content="凡是存在的就是合理的，那些说函数式编程可读性差的，你就是不会啊！">
<meta property="og:updated_time" content="2016-11-22T09:15:35.302Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="函数式编程:用自带的js原型链方法解决问题">
<meta name="twitter:description" content="凡是存在的就是合理的，那些说函数式编程可读性差的，你就是不会啊！">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 6342361719439885000,
      author: '作者'
    }
  };
</script>

  <title> 函数式编程:用自带的js原型链方法解决问题 | jackfred的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?b3de569bd7de0e2a0f7fdae181ff03da";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta custom-logo">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">jackfred的博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">人啊,就是需要一点亮剑精神</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                函数式编程:用自带的js原型链方法解决问题
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-23T12:28:21+08:00" content="2016-10-23">
              2016-10-23
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/博客/" itemprop="url" rel="index">
                    <span itemprop="name">博客</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/10/23/函数式编程-用自带的js原型链方法解决问题/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/10/23/函数式编程-用自带的js原型链方法解决问题/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>凡是存在的就是合理的，那些说函数式编程可读性差的，你就是不会啊！<br><a id="more"></a><br>其实代码写久了，有时候会对一个非常长的代码文件产生厌烦感，在阅读别人的代码或者回顾自己以前写的代码时候更是如此。<br>当你阅读到一个长长的for循环而没有注释这个for是用来干啥时，内心的戾气就更是要爆发出来。其实很多情况我们是没有必要写出这种臃肿的代码的，函数式也是可以做到。</p>
<h1 id="前提"><a href="#前提" class="headerlink" title="前提"></a>前提</h1><p>本篇会深入浅出的指出日常代码可以简化的地方，包括但是不止函数式编程，在以后的文章里，我们还会进一步探讨函数式编程的各种运用。</p>
<h1 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h1><p>在实际编码的过程中会遇到很多类数组的数据，或者一个长字符串排序等问题，以此我们可以接住数组中自带的原型方法去解决问题。</p>
<h2 id="Array-prototype-every"><a href="#Array-prototype-every" class="headerlink" title="Array.prototype.every()"></a>Array.prototype.every()</h2><p>这个方法是用来测试数组的所有元素是否都通过了指定函数的测试</p>
<blockquote>
<p>every 方法为数组中的每个元素执行一次 callback 函数，直到它找到一个使 callback 返回 false（表示可转换为布尔值 false 的值）的元素。如果发现了一个这样的元素，every 方法将会立即返回 false。否则，callback 为每一个元素返回 true，every 就会返回 true。callback 只会为那些已经被赋值的索引调用。不会为那些被删除或从来没被赋值的索引调用。<br>callback 被调用时传入三个参数：元素值，元素的索引，原数组。</p>
</blockquote>
<p>举个例子</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">// 检测数组中是否全都小于100的数字</div><div class="line">var flag = [1，32，55，67，98，101，33，44，43].every(function(item， index， array)&#123;</div><div class="line">	return item &lt;= 100</div><div class="line">&#125;)</div><div class="line">console.log(flag) //结果为false，101大于100</div></pre></td></tr></table></figure>
<p>通过这个例子我们已经看到every的作用，下面看看在实际场景中的运用<br>我们在写复选框组这个组件的时候，有一个“全选”这个复选框，当我们在手动勾选全部的子复选框时，全选框会自动勾选上，取消其中一个的时候，全选框就会取消勾选，在实际编码过程中，我们可能要写一个for循环来轮询一遍每个子组件的状态，现在我们可以用every实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">var allCheckBoxDom = document.getElementsByClassName(&apos;quanxuan&apos;)[0] //获取全选复选框</div><div class="line">var childrenCheckBoxDoms = document.getElementsByClassName(&apos;zixuanze&apos;) //获取子选择框组，这是一个类数组</div><div class="line">var flag = [].every.call(childrenCheckBoxDoms， function(item， index， array) &#123;</div><div class="line">	item.checked === true</div><div class="line">&#125;)</div><div class="line">if(flag)&#123;</div><div class="line">	allCheckBoxDom.checked = true;</div><div class="line">&#125;else&#123;</div><div class="line">	allCheckBoxDom.checked = false;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这样就方便的实现了这个功能</p>
<blockquote>
<p>对应的方法有Array.prototype.some()，其作用是只要数组中有一个满足条件，就会返回true，用法与every相同，在这里就不赘述了</p>
<h2 id="Array-prototype-map"><a href="#Array-prototype-map" class="headerlink" title="Array.prototype.map()"></a>Array.prototype.map()</h2><p>这个方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。<br>举个例子<br>我们通过ajax获取到的一组数据，类似这样的<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">var jobs = [</div><div class="line">	&#123;name:&apos;zk&apos;，age:22&#125;</div><div class="line">	&#123;name:&apos;ab&apos;，age:12&#125;</div><div class="line">	&#123;name:&apos;cd&apos;，age:33&#125;</div><div class="line">	&#123;name:&apos;pol&apos;，age:5&#125;</div><div class="line">]</div></pre></td></tr></table></figure></p>
</blockquote>
<p>如果我们想把这个数组里面的name提取出来组成一个数组，可以这样做<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">var nameList = jobs.map(function(item， index， array)&#123;</div><div class="line">	return item.name</div><div class="line">&#125;)</div></pre></td></tr></table></figure></p>
<h2 id="Array-prototype-reduce"><a href="#Array-prototype-reduce" class="headerlink" title="Array.prototype.reduce()"></a>Array.prototype.reduce()</h2><p>这个方法接收一个函数作为累加器（accumulator），数组中的每个值（从左到右）开始合并，最终为一个值。<br>也就是说是一种迭代器，另一种意义上的for循环，它传给callback函数的参数有四个，分别是<br>previousValue 上一次调用回调返回的值，或者是提供的初始值（initialValue）<br>currentValue 数组中当前被处理的元素<br>index 当前元素在数组中的索引<br>array 调用 reduce 的数组<br>另外reduce还可以接受一个初始值<br>举个例子<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">[1，2，3，4].reduce(function(previousValue， currentValue， index， array)&#123;</div><div class="line">	return previousValue + currentValue</div><div class="line">&#125;)</div></pre></td></tr></table></figure></p>
<p>其结果就是把数组里面的值求和，结果是10，如果给redece加一个初始值<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">[1，2，3，4].reduce(function(previousValue， currentValue， index， array)&#123;</div><div class="line">	return previousValue + currentValue</div><div class="line">&#125;，5)</div></pre></td></tr></table></figure></p>
<p>这样子结果就是15</p>
<h1 id="Math"><a href="#Math" class="headerlink" title="Math"></a>Math</h1><p>Math是js自带的一个数学库，可以方便的做各种计算，我们编码过程中可以巧妙借用他来实现功能，避免冗余的代码。</p>
<h2 id="Math-max"><a href="#Math-max" class="headerlink" title="Math.max"></a>Math.max</h2><p>看名字你们也知道和Math.min对应，求最大值，简单的用法是直接传值<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">console.log(Math.max(1，2，4，5，6，7)) //输出7</div></pre></td></tr></table></figure></p>
<p>但是如果我们用于数组，就可以很简单的求出一个数组里面的最大值（或者最小值）<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">var array = [44，12，42，11，87，33，49，3，487，111]</div><div class="line">var maxNum = Math.max.call(Math， array)</div><div class="line">console.log(maxNum) //输出487</div></pre></td></tr></table></figure></p>
<h2 id="Math-min"><a href="#Math-min" class="headerlink" title="Math.min"></a>Math.min</h2><p>和Math.max用法相同，不再赘述</p>
<h1 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h1><p>函数式编程还有很多用法，这只是第一篇，我会在以后的文章里面介绍更多的用法。</p>

      
    </div>

    <div>
      
        
      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/数组/" rel="tag">#数组</a>
          
            <a href="/tags/Math/" rel="tag">#Math</a>
          
            <a href="/tags/函数式编程/" rel="tag">#函数式编程</a>
          
            <a href="/tags/原型链/" rel="tag">#原型链</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/22/postman奇技淫巧/" rel="next" title="postman奇技淫巧">
                <i class="fa fa-chevron-left"></i> postman奇技淫巧
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/24/关于博客内容的想法/" rel="prev" title="关于博客内容的想法">
                关于博客内容的想法 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <div class="ds-share flat" data-thread-key="2016/10/23/函数式编程-用自带的js原型链方法解决问题/"
     data-title="函数式编程:用自带的js原型链方法解决问题"
     data-content=""
     data-url="https://zk-.github.io/2016/10/23/函数式编程-用自带的js原型链方法解决问题/">
  <div class="ds-share-inline">
    <ul  class="ds-share-icons-16">

      <li data-toggle="ds-share-icons-more"><a class="ds-more" href="javascript:void(0);">分享到：</a></li>
      <li><a class="ds-weibo" href="javascript:void(0);" data-service="weibo">微博</a></li>
      <li><a class="ds-qzone" href="javascript:void(0);" data-service="qzone">QQ空间</a></li>
      <li><a class="ds-qqt" href="javascript:void(0);" data-service="qqt">腾讯微博</a></li>
      <li><a class="ds-wechat" href="javascript:void(0);" data-service="wechat">微信</a></li>

    </ul>
    <div class="ds-share-icons-more">
    </div>
  </div>
</div>
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/10/23/函数式编程-用自带的js原型链方法解决问题/"
           data-title="函数式编程:用自带的js原型链方法解决问题" data-url="https://zk-.github.io/2016/10/23/函数式编程-用自带的js原型链方法解决问题/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="周康" />
          <p class="site-author-name" itemprop="name">周康</p>
          <p class="site-description motion-element" itemprop="description">运动与认知是人生最重要的两件事</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">14</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">2</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">26</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zk-" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/jackfredzk" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/zhou-kang-46-86" target="_blank" title="Zhihu">
                  
                    <i class="fa fa-fw fa-quote-left"></i>
                  
                  Zhihu
                </a>
              </span>
            
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前提"><span class="nav-number">1.</span> <span class="nav-text">前提</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#数组"><span class="nav-number">2.</span> <span class="nav-text">数组</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-every"><span class="nav-number">2.1.</span> <span class="nav-text">Array.prototype.every()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-map"><span class="nav-number">2.2.</span> <span class="nav-text">Array.prototype.map()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array-prototype-reduce"><span class="nav-number">2.3.</span> <span class="nav-text">Array.prototype.reduce()</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Math"><span class="nav-number">3.</span> <span class="nav-text">Math</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Math-max"><span class="nav-number">3.1.</span> <span class="nav-text">Math.max</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Math-min"><span class="nav-number">3.2.</span> <span class="nav-text">Math.min</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#结语"><span class="nav-number">4.</span> <span class="nav-text">结语</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">周康</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.2"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"jackfred"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
      
      <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
      <script src="/js/src/hook-duoshuo.js"></script>
    
  





  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  

</body>
</html>
